package service

import (
	"context"
	"password-verification-management-system/cache"
	"password-verification-management-system/dao"
	"password-verification-management-system/model"
	"password-verification-management-system/serializer"
	"password-verification-management-system/utills"
	"time"
)

type AdminService struct {
	UserName string `form:"username" json:"username"`
	Password string `form:"password" json:"password"`
	Email    string `form:"email" json:"email"`
	Phone    string `form:"phone" json:"phone"`
	UserType string `form:"usertype" json:"usertype"`
	Key      string `form:"key" json:"key"` // 前端进行判断
	Code     string `form:"code" json:"code"`
}

func (service AdminService) AdminRegister(ctx context.Context) serializer.Response {
	adminDao := dao.NewAdminDao(ctx)
	admin := model.Admin{
		Username: service.UserName,
		Usertype: "guest",
		Password: service.Password,
		Email:    service.Email,
	}
	err := adminDao.CreateAdmin(&admin)
	if err != nil {
		return serializer.Response{
			Status: 401,
			Msg:    "创建admin失败",
		}
	}
	return serializer.Response{
		Status: 200,
		Msg:    "创建admin成功",
	}

}

func (service AdminService) AdminGetCode(ctx context.Context) serializer.Response {
	admindao := dao.NewAdminDao(ctx)
	admin, err := admindao.GetAdminEmailByName(service.UserName)
	if err != nil {
		return serializer.Response{
			Status: 401,
			Msg:    "查询用户邮箱失败",
		}
	} else {
		returncode := utills.SendEmailAddr(admin.Email)
		redisclient := cache.RedisClient
		redisclient.Set(ctx, service.UserName, returncode, time.Minute*5)
		//returncode := email.SendMailQQ(admin.Email)
		return serializer.Response{
			Status: 200,
			Msg:    "发送验证码成功",
		}
	}

}

func (service AdminService) AdminLogin(ctx context.Context) interface{} {
	admindao := dao.NewAdminDao(ctx)
	admin, exist, err := admindao.ExistOrNotByAdminName(service.UserName)
	if err != nil {
		if !exist { //如果查询不到，返回相应的错误
			return serializer.Response{
				Status: 400,
				Msg:    "无相关用户",
			}
		} else {
			return serializer.Response{
				Status: 400,
				Msg:    "查询错误",
			}
		}
	}
	redisclient := cache.RedisClient
	stringCmd := redisclient.Get(ctx, admin.Username)
	if (admin.Username) == "" || stringCmd.Val() != service.Code {
		return serializer.Response{
			Status: 400,
			Msg:    "验证码错误",
		}
	}
	token, err := utills.ReleaseToken(admin.ID, admin.Usertype)
	if err != nil {
		return serializer.Response{
			Status: 400,
			Msg:    "token 签发错误",
		}
	}
	return serializer.Response{
		Status: 200,
		Data:   serializer.TokenData{User: admin.ID, Token: token},
		Msg:    "登录成功",
	}

}
